/**
 * 
 */
package zh.guocw.hc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SocketChannel;

/**
 * @author GuoChangwei
 *
 */
public abstract class AbstractSession {
	private InetSocketAddress remoteAddress;
	private InetSocketAddress localAddress;
	// HTTP Client side SelectableChannel
	private SocketChannel clientChannel;
	
	/**
	 * @param remoteHost
	 * @param remotePort A valid port value is between 0 and 65535. A port number of zero will let the system pick up an ephemeral port in a bind operation. 
	 * @param localHost
	 * @param localPort A valid port value is between 0 and 65535. A port number of zero will let the system pick up an ephemeral port in a bind operation. 
	 * @throws IOException 
	 * */
	public AbstractSession(String remoteHost,int remotePort,String localHost,int localPort) throws IOException{
		this.remoteAddress = new InetSocketAddress(remoteHost, remotePort);
		this.localAddress = new InetSocketAddress(localHost, localPort);
		this.clientChannel = SocketChannel.open();
		prepareChannel();
	}
	
	
	public AbstractSession(InetSocketAddress remoteAddress, InetSocketAddress localAddress) throws IOException {
		super();
		this.remoteAddress = remoteAddress;
		this.localAddress = localAddress;
		this.clientChannel = SocketChannel.open();
		prepareChannel();
	}

	/**
	 * initial the HTTP Client side SelectableChannel.
	 * 
	 * bind local IP or Frame IP.
	 * 
	 * connect to remote server.
	 * @throws IOException 
	 * 
	 * */
	public void prepareChannel() throws IOException{
		/* initial the SocketChannel of this session :  */
		//socket associated with this SocketChannel
		System.out.println("==prepareChannel start==");
		Socket socket = this.clientChannel.socket();
		socket.setReuseAddress(true);
		//Increasing the receive buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data. 
		socket.setReceiveBufferSize(1024*50);
		socket.bind(localAddress);
		
		//set non-block 
		this.clientChannel.configureBlocking(false);
		this.clientChannel.connect(remoteAddress);
		System.out.println("==prepareChannel end==");
	}

	public SocketAddress getRemoteAddress() {
		return remoteAddress;
	}

	public SocketAddress getLocalAddress() {
		return localAddress;
	}

	public SelectableChannel getClientChannel() {
		return clientChannel;
	}
	
	
}
